//
//  MH2ViewController.m
//  FlickrSearching
//
//  Created by Lam Quoc on 4/25/15.
//  Copyright (c) 2015 HOCVIEN. All rights reserved.
//

#import "MH2ViewController.h"
#import "MH2TableViewCell.h"
#import "FavoriteViewController.h"
@interface MH2ViewController ()

@end

@implementation MH2ViewController
NSDictionary* myDictionary;
NSDictionary* myPhotoDic;
NSArray* myArray;
NSArray* filteredList;
bool usingSearchBar;
NSString* favoritesID;
NSString* ownerID;
- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
    self.myTableView.dataSource=self;
    self.myTableView.delegate=self;
    filteredList = [[NSMutableArray alloc]init];
    //https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=c3b58fe7db5ef03eac37c1dbe69d8917&place_id=6dCBhRRTVrJiB5xOrg&extras=url_t%2C+owner_name%2C+description&format=json&nojsoncallback=1&api_sig=97e3a0e093383402b1b4bee9d236002f
     NSString*  placeID =  [[NSUserDefaults standardUserDefaults] objectForKey:@"an"];
    
    if (placeID == nil) {
        placeID = @"6dCBhRRTVrJiB5xOrg";
        NSLog(@"placeID is nil");
    }

    
    NSString* urlString = [NSString stringWithFormat:@"https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=089afbc8ab4344f419308ffb088b8f7c&place_id=%@",placeID];
    urlString = [urlString stringByAppendingString:@"&extras=url_t%2C+owner_name%2C+description&format=json&nojsoncallback=1"];
    
    //NSLog(@"url String : %@",urlString);
    
    NSURL* url=[[NSURL alloc]initWithString:urlString];
    NSURLRequest* request = [[NSURLRequest alloc]initWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (!connectionError) {
            //NSLog(@"Data : %@",data);
            //NSLog(@"REspone :%@",response);
            
            NSError* myError;
            if (!myError) {
                myDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&myError];
                myPhotoDic = [myDictionary objectForKey:@"photos"];
                myArray = [myPhotoDic objectForKey:@"photo"];
            }
            else{
                NSLog(@"%@",myError);
            }
            
            //NSLog(@"%@",[myArray description]);
            [self.myTableView reloadData];
            
        }else{
            //NSLog(@"%@",connectionError);
        }
    }];

    usingSearchBar=NO;
    self.mySearchBar.showsCancelButton=NO;
    
//    UIActivityIndicatorView* myActivity = [[UIActivityIndicatorView alloc]init];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (usingSearchBar==NO)  {
        return myArray.count;
    }else{
        return filteredList.count;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MH2TableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:@"Cell" ];
    [cell.mh2Activity startAnimating];

    //Xet mau cho cell
    if (indexPath.row%2==0) {
        [cell setBackgroundColor:[UIColor lightGrayColor]];
    }else{
        [cell setBackgroundColor:[UIColor whiteColor]];
    }
    
    NSDictionary* photoDic;
    if (usingSearchBar==NO)  {
        //TableView
        photoDic = [myArray objectAtIndex:indexPath.row];
        
        //NSLog(@"%@",[myArray description]);
    }else{
        //Search Bar
        self.mySearchBar.showsCancelButton=YES;
        photoDic = [filteredList objectAtIndex:indexPath.row];
    }
    
    cell.titlePhoto.text =[photoDic objectForKey:@"title"];
    cell.authorPhoto.text =[photoDic objectForKey:@"ownername"];
    favoritesID = [photoDic objectForKey:@"id"];
    ownerID = [photoDic objectForKey:@"owner"];
    NSString* urlString = [photoDic objectForKey:@"url_t"];
    
    dispatch_async(dispatch_queue_create("ImageLoad", nil), ^{
        NSURL *url=[[NSURL alloc] initWithString:urlString];
        NSData* myData = [[NSData alloc]initWithContentsOfURL:url];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            cell.myImage.image = [UIImage imageWithData:myData];
            [cell.mh2Activity stopAnimating];
        });
        
    });

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary* photoDic;
    if (usingSearchBar==NO)  {
        //TableView
        photoDic = [myArray objectAtIndex:indexPath.row];
        
        //NSLog(@"%@",[myArray description]);
    }else{
        //Search Bar
        self.mySearchBar.showsCancelButton=YES;
        photoDic = [filteredList objectAtIndex:indexPath.row];
    }
    
    
    NSString *title, *canncel;
    title = @"Notice"; canncel = @"Cancel";
    //Khởi tạo 1 actionSheet
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:title delegate:self cancelButtonTitle:canncel destructiveButtonTitle:nil otherButtonTitles:@"Favorites", [NSString stringWithFormat:@"%@'s photos",[photoDic objectForKey:@"ownername"]],[NSString stringWithFormat:@"%@'s album",[photoDic objectForKey:@"ownername"]], nil];
    //Hiển thị 1 actionSheets
    [actionSheet showInView:self.view];
    //NSLog(@"%d",(int)indexPath.row);
    
}
#pragma  mark - actionSheet
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
        {
            [[NSUserDefaults standardUserDefaults] setObject:favoritesID forKey:@"favoritesID"];
            NSLog(@"ID picture : %@",favoritesID);
            FavoriteViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"favoriteID"];
            
            [self.navigationController pushViewController:vc animated:YES];        }
            break;
        case 1:
             [[NSUserDefaults standardUserDefaults] setObject:ownerID forKey:@"ownerID"];
            NSLog(@"ID ownerID : %@",ownerID);
            break;
        case 2:
            [[NSUserDefaults standardUserDefaults] setObject:ownerID forKey:@"ownerID"];
            NSLog(@"ID ownerID : %@",ownerID);
            break;
        default:
            break;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(void)filterContentForSearchText:(NSString*)searchText
{
//    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"title contains[cd] %@", searchText];
//    filteredList = [myArray filteredArrayUsingPredicate:resultPredicate];
    
    
//    NSDictionary* myDic;
//    for (int i = 0; i< myArray.count; i++) {
//        myDic = myArray[i];
//        if ([[myDic objectForKey:@"title"] isEqualToString:scope]) {
//            [filteredList addObject:myArray[i]];
//        }
//    }
    
    filteredList = nil;
    NSPredicate *resultsPredicate;
    resultsPredicate = [NSPredicate predicateWithFormat:@"SELF.title contains [search] %@",searchText];
    filteredList = [[myArray filteredArrayUsingPredicate:resultsPredicate] mutableCopy];
    //NSLog(@"%@",[filteredList description]);
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    usingSearchBar=NO;
    self.mySearchBar.showsCancelButton=NO;
    [self.myTableView reloadData];
}

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    NSString *text1 = [searchBar.text stringByReplacingCharactersInRange:range withString:text];
    
    if ([text1 isEqualToString:@" "]) {
        return NO;
    }
    
    usingSearchBar = (text.length < 1)?NO:YES;
//    usingSearchBar = (text.length > 0);
    
    [self filterContentForSearchText:text1 ];
    [self.myTableView reloadData];
    return YES;
}



@end
